/**
 * The class GraphPlotter plots a graph with the plot data. The plot data is an
 * object with ngram keys and time series values. A plot is created with time
 * series for every ngram in the object.
 *
 * ngram_data: An NgramData object.
 * graph_div: The div to which the graph must be attached to.
 * legend_div: The div to attach the legend to.
 *
 * slider_div: The div where the slider will be attached to.
 * slider_label_div: The div to attach the slider's tooltip to.
 */
function GraphPlotter( ngram_data, graph_div, legend_div, slider_div, slider_label_div ) {
  qwerty = this;
  var graph = this;
    
  this.ngram_data = ngram_data;
  this.graph_div = graph_div;
  this.legend_div = legend_div;
  this._initMinMaxYears();
  
  // Slider Functionality.
  // Peg the starting points to 1800 and 2000
  var thisMin = this.start_year;
  var thisMax = this.end_year;
  if (1800 > thisMin && 1800 < thisMax) {
      this.start_year = 1800;
  }
  if (2000 > thisMin && 2000 < thisMax) {
      this.end_year = 2000;
  }
  
  this.slider_div = slider_div;
  this.slider_label_div = slider_label_div;
  var slider_options = {
    range: true,
    min: Number(thisMin),
    max: Number(thisMax),
    //values: [ Number(this.start_year), Number(this.end_year) ],
    values: [ 1800, 2000 ],
    slide: function( event, ui) {
      graph.start_year = graph.slider_div.slider( "values", 0 );
      graph.end_year = graph.slider_div.slider( "values", 1 );
      graph.slider_label_div.html(graph.start_year + " - " + graph.end_year);
      graph.Plot();
    },
    change: function( event, ui) {
      graph.start_year = graph.slider_div.slider( "values", 0 );
      graph.end_year = graph.slider_div.slider( "values", 1 );
      graph.slider_label_div.html(graph.start_year + " - " + graph.end_year);
      graph.Plot();
    }
  }
  this.slider_div.slider(slider_options);
  this.slider_label_div.html(this.start_year + " - " + this.end_year);
  // End of Slider Functionality.
}

GraphPlotter.prototype.Plot = function() {
  var thisGraphPlotter = this;
  
  //TODO: Hacky ...
  this.ngram_data.start_year = this.start_year;
  this.ngram_data.end_year = this.end_year;
  var all_data = this.ngram_data.GetPlotData(true);
  
  var scaling_factor = all_data[1];
  var plot_data = all_data[0];
  var all_time_series = new Array();
  
  $.each(plot_data, function(key, value) {
    all_time_series.push({label: key, data: value});
  });
  var plot_obj = $.plot(thisGraphPlotter.graph_div, all_time_series, {
    yaxis: { min: 0 },
    xaxis: { min: this.start_year, max: this.end_year },
    legend: {container: this.legend_div, noColumns: 10},
    grid: { hoverable: true },
    series: { lines: { show:true } }
  });
  //this.legend_div.find("td").css("border","0px"); //Needed on WhoIsBigger to get rid of ugly CSS

  //ToolTip Handling
  this.lastHover = null; //Reset
  this.graph_div.unbind(); //Unbind previous handler
  this.graph_div.bind("plothover", function (event, pos, item) {
      if (thisGraphPlotter.lastHover != null && item && thisGraphPlotter.lastHover.datapoint[0] == item.datapoint[0]) return;
      $("#tooltip").remove(); plot_obj.unhighlight();
      if (item) {
          var series = plot_obj.getData();
          var tooltip_html = item.datapoint[0] + "<table>";
          var x = item.datapoint[0];
          for (var i = 0; i < series.length; i++) {
              var datapoint = find(x, series[i].data);
              if (datapoint != null) {
                    plot_obj.highlight(series[i], datapoint);
                    var y = datapoint[1];
                    if (thisGraphPlotter.ngram_data.scale) y *= scaling_factor;
                    if (thisGraphPlotter.ngram_data.normalize) y *= thisGraphPlotter.ngram_data.GetNormalizationForYear(x);
                    if (series[i] == item.series) {
                        tooltip_html += "<tr><td>\u2022&nbsp;<b>" + series[i].label + "</b></td><td><b>" + Math.round(y) + "</b></td></tr>"; 
                    } else {
                        tooltip_html += "<tr><td>" + series[i].label + "</td><td>" + Math.round(y) + "</td></tr>";
                    }
              }
          }
          tooltip_html += "</table>";
          showTooltip(item.pageX, item.pageY, tooltip_html);
          thisGraphPlotter.lastHover = item;
      } else {
          thisGraphPlotter.lastHover = null;
      }
  });
};

GraphPlotter.prototype._initMinMaxYears = function() {
  var min_a = 5000, max_a = -5000;
  $.each(this.ngram_data.GetPlotData(false), function(key, value) {
    var locMin = getMinYear(value);
    var locMax = getMaxYear(value);
    if (locMin < min_a) min_a = locMin;
    if (locMax > max_a) max_a = locMax;
  });
  this.start_year = min_a;
  this.end_year = max_a;
};

function find(year, data) {
  var ret = null;
  $.each(data, function(index, yeardata) {
      if (yeardata[0] == year) {
          ret = yeardata;
          return false;
      }
      return true;
  });
  return ret;
}

function showTooltip(x, y, contents) {        
    $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80,
        'z-index': 5
    }).appendTo("body").fadeIn(50);
}